﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FAP.DataAccess.BLL;
using FAP.DataAccess;
using FAP.Cores.Task;
using System.Text.RegularExpressions;
using System.Threading;

namespace FAP.Uppers.UC
{
    public partial class ucUpper : UserControl
    {
        private List<DataAccess.BLL.baiviet> dsbaiviet;
        public ucUpper()
        {
            InitializeComponent();
            ucListThread1.onSelectedWebSite += new GUI.UC.ucListThread.SelectedHandler(ucListThread1_onSelectedWebSite);
        }

        void ucListThread1_onSelectedWebSite(List<DataAccess.BLL.baiviet> sender)
        {
            
            if (sender.Count == 0)
            {
                MessageBox.Show("Chưa chọn link để up");
            }
            {
                
                //dsbaiviet.Clear();
                dsbaiviet = sender;
            }
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            lvStateUP.Items.Clear();
            dsbaiviet = ucListThread1.GetSelectedThred();
            if (dsbaiviet.Count == 0)
            {
                MessageBox.Show("Chưa chọn link để up");
            }
            else
            {
                for (int i = 0; i < dsbaiviet.Count; i++)
                {
                    int iTempt = dsbaiviet[i].link.IndexOf("&p=");
                    if (iTempt != -1)
                    {
                        dsbaiviet[i].link = dsbaiviet[i].link.Remove(iTempt);
                    }
                    nghiepvu nv = new nghiepvu();
                    nv.id = 4;
                    chitietnghiepvu ctngvu = new chitietnghiepvu();
                    ctngvu.nghiepvuid = nv.id;
                    taikhoan tk = new taikhoan();
                    string linkweb = dsbaiviet[i].link;//fix cứng bá đạo quá
                    tk = taikhoan.taikhoanSelectRow_CanUp(dsbaiviet[i].id);

                    string title = "hello";

                    int websiteID = dsbaiviet[i].websiteId;//khoan

                    ctngvu = chitietnghiepvu.chitietnghiepvuSelectRowByForeignKey_nghiepvuid_websiteid(4, websiteID).SingleOrDefault();

                    UpTask obj_up = new UpTask(ctngvu, this.txtContentUp.Text, linkweb, dsbaiviet[i].link, title , dsbaiviet[i].id);
                    obj_up.m_tk = tk;
                    obj_up.onFinished += onFinished;
                    obj_up.onError += onError;
                    obj_up.TimeToRepeat = 100;
                    
                    //Thread.Sleep(30000);
                    //content = obj_up.LastHTML;
                    if (m_lstTask.Where(m => m.LinkThread == obj_up.LinkThread).Count() == 0)
                    {
                       
                        int SoNghiepVuCungTrang = m_lstTask.Where(m => m.ChiTietNghiepVu.websiteid == ctngvu.websiteid).Count();
                        obj_up.TimeToWaitForNext = SoNghiepVuCungTrang * 40;
                        FAP.Cores.Threading.ThreadControl.AddTasks(obj_up);
                        m_lstTask.Add(obj_up);
                    }
                }
                
            }

        }

        private List<UpTask> m_lstTask = new List<UpTask>();

        private void onChangeStatus(object sender, object result)
        {
            Console.WriteLine("FUCK");
            //Console.ReadKey();// throw new NotImplementedException();
        }
        private  void onError(object sender, object result)
        {
            MessageBox.Show("Fuckkkkkkkkkkkkkkkkkkkkkkkkkkk");
            // throw new NotImplementedException();
        }
        string t;
        int tt = 1;
        //cookieuser=1&cookie=0&securitytoken=1384078178-40bc796eac08fc5e51b96d49d36da7215f3996ad&ajax=1&ajax_lastpost=1384077765&message_backup=jknnkjnkjnfdsdd&message=jknnkjnkjnfdsdd&wysiwyg=0&fromquickreply=1&s=&securitytoken=1384078178-40bc796eac08fc5e51b96d49d36da7215f3996ad&do=postreply&t=104&p=who%20cares&specifiedpost=0&parseurl=1&loggedinuser=12&posthash=2527bb49eaee7710e7e8c28e19569e98&poststarttime=1384077832
        //cookieuser=1&cookie=0&prefixid=&securitytoken=1384078498-6ff9449d0f25c4c0573d398ad13a61470e187404&subject=http://www.vn-zoom.com/newthread.php?do=newthread&f=399&message=Up Up Up Up Up Up !!&f=7&s=&loggedinuser=1&currforum=on&titlesonly=on&wysiwyg=0&taglist=&iconid=0&do=postthread&posthash=&poststarttime=&sbutton=G%e1%bb%9fi+%c3%90%e1%bb%81+T%c3%a0i+M%e1%bb%9bi&parseurl=1&emailupdate=9999&polloptions=4&vbseo_retrtitle=1&vbseo_is_retrtitle=1&signature=1
        private  void onFinished(object sender, object result)
        {
            UpTask pt = (UpTask)sender;

            if (pt.LastHTML != null)
            {
                t = pt.LastHTML;
                //vbb---------------------
                if (pt.LastHTML.IndexOf("vBulletin&reg") != -1 || pt.LastHTML.IndexOf("vBulletin&trade") != -1 && pt.response.ResponseUri != pt.requester.uri)
                {
                    string[] arr = new string[3];
                    ListViewItem itm;

                    //Add first item
                    arr[0] = "Thành Công";
                    arr[1] = pt.response.ResponseUri.ToString();
                    itm = new ListViewItem(arr);
                    this.Invoke((MethodInvoker)delegate
                    {
                        lvStateUP.Items.Add(itm);
                        //comment.commentInsertRow(pt.m_tk.id, (pt.Idbaivietcsdl), pt.response.ResponseUri.ToString(), "", "hello", pt.Content, DateTime.Now, false);
                    });
                }
                //-------------------------

                //xenforo--------------
                else 
                {
                    string html = Regex.Unescape(pt.LastHTML);
                    string[] arr = new string[3];
                    ListViewItem itm;
                    int pos = html.LastIndexOf("threads/"+pt.LinkThread.Split('/')[4]+"/#post-");
                    if (pos != -1)
                    {
                        string[] arr1 = new string[3];
                        ListViewItem itm1;
                        tt = 0;
                        //Add first item
                        arr[0] = "Fail - Đã up quá 3 lần";
                        arr[1] = pt.LinkThread;
                        itm1 = new ListViewItem(arr1);
                        this.Invoke((MethodInvoker)delegate
                        {
                            lvStateUP.Items.Add(itm1);
                            //comment.commentInsertRow(pt.m_tk.id, (pt.Idbaivietcsdl), linkdaup, "", "hello", pt.Content, DateTime.Now, false);
                        });
                        return;
                    }
                    else
                    {
                        string temp = "";
                        temp = html.Substring(pos);
                        temp = temp.Split('\"')[0];
                        //temp = temp.Split('/')[2];

                        string linkdaup = pt.requester.uri.Authority.ToString() +"/"+temp;
                        // chen du lieu vao linkdaup;
                        //Add first item
                        arr[0] = "Thành Công";
                        arr[1] = linkdaup;
                        itm = new ListViewItem(arr);
                        this.Invoke((MethodInvoker)delegate
                        {
                            lvStateUP.Items.Add(itm);
                            comment.commentInsertRow(pt.m_tk.id, (pt.Idbaivietcsdl), linkdaup, "", "hello", pt.Content, DateTime.Now, false);
                        });
                    }
                }
                //---------------------
                
            }
            else
            {
                tt = 0;
                string[] arr = new string[3];
                ListViewItem itm;

                //Add first item
                arr[0] = "Thất bại";
                arr[1] = pt.LinkThread;
                itm = new ListViewItem(arr);
                lvStateUP.Items.Add(itm);

            }

            //if (pt.LastHTML.ToLower().IndexOf("\"_redirectStatus\":\"ok\"".ToLower()) != -1)
            //{

            //    string linkdaUp = "";
            //    linkdaUp = pt.TimKiem(Regex.Unescape(pt.LastHTML), "posts/");
            //    //===============================
            //    // lay link bai viet truyen vào
            //    //linkdaUp = pt.LinkThread + "#post-" + linkdaUp;
            //    //===============================
            //    linkdaUp = linkdaUp.Remove(linkdaUp.Length - 1);

            //    //Add items in the listview
            //    string[] arr = new string[3];
            //    ListViewItem itm;

            //    //Add first item
            //    arr[0] = "Thành Công";
            //    arr[1] = linkdaUp;
            //    itm = new ListViewItem(arr);
            //    lvStateUP.Items.Add(itm);
            //    //Console.WriteLine(linkdaUp);
            //    //Console.ReadKey();
            //}
            //else
            //{
                
            //    string[] arr = new string[3];
            //    ListViewItem itm;

            //    //Add first item
            //    arr[0] = "Thất bại";
            //    arr[1] = pt.LinkThread.ToString();
            //    itm = new ListViewItem(arr);
            //    lvStateUP.Items.Add(itm);

            //}

            //if (pt.LastHTML.IndexOf("vBulletin&reg") != -1 || pt.LastHTML.IndexOf("vBulletin&trade") != -1) // dien dan vbb
            //{
            //    if (pt.LastHTML != null)
            //    {
            //        string[] arr = new string[3];
            //        ListViewItem itm;

            //        //Add first item
            //        arr[0] = "Thành Công";
            //        arr[1] = pt.response.ResponseUri.ToString();
            //        itm = new ListViewItem(arr);
            //        lvStateUP.Items.Add(itm);
                    
            //    }
            //    else
            //    {
            //        string[] arr = new string[3];
            //        ListViewItem itm;

            //        //Add first item
            //        arr[0] = "Thất bại";
            //        arr[1] = pt.LinkThread;
            //        itm = new ListViewItem(arr);
            //        lvStateUP.Items.Add(itm);

            //    }
            //}
            //else // dien dan xenforo
            //{
            //    if (pt.LastHTML.ToLower().IndexOf("\"_redirectStatus\":\"ok\"".ToLower()) != -1)
            //    {

            //        string linkdaUp = "";
            //        linkdaUp = pt.TimKiem(Regex.Unescape(pt.LastHTML), "posts/");
            //        //===============================
            //        // lay link bai viet truyen vào
            //        //linkdaUp = pt.LinkThread + "#post-" + linkdaUp;
            //        //===============================
            //        linkdaUp = linkdaUp.Remove(linkdaUp.Length - 1);

            //        //Add items in the listview
            //        string[] arr = new string[3];
            //        ListViewItem itm;

            //        //Add first item
            //        arr[0] = "Thành Công";
            //        arr[1] = linkdaUp;
            //        itm = new ListViewItem(arr);
            //        lvStateUP.Items.Add(itm);
            //        //Console.WriteLine(linkdaUp);
            //        //Console.ReadKey();
            //    }
            //    else
            //    {
            //        string linkdaUp = "Up thất bại";
            //        string[] arr = new string[3];
            //        ListViewItem itm;

            //        //Add first item
            //        arr[0] = "Thất bại";
            //        arr[1] = pt.LinkThread.ToString();
            //        itm = new ListViewItem(arr);
            //        lvStateUP.Items.Add(itm);
                    
            //    }
            //}

        }

        private void lvStateUP_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int index = lvStateUP.SelectedIndices[0];
            if (index >= 0 && tt == 1)
            {
                String url = lvStateUP.Items[index].SubItems[1].Text;
                FrmBrowser frmBrowser = new FrmBrowser();
                frmBrowser.Url = url;
                frmBrowser.ShowDialog();
            }
            else
            {
                String url = t;
                FrmBrowser frmBrowser = new FrmBrowser();
                frmBrowser.Url = url;
                frmBrowser.ShowDialog();
            }
        }
        

    } 
}
